﻿using System;
using System.Collections.Generic;

namespace Mars.Network
{
    public class MessageHandler
    {
        /// <summary>
        /// 消息处理对象队列
        /// </summary>
        private readonly Queue<MessageObject> m_MessageObjects = new Queue<MessageObject>();

        private Type m_MessageType;
        
        private Action<MessageObject> m_Handler;
        
        public MessageHandler(Type messageType)
        {
            m_MessageType = messageType;
            m_Handler = null;
        }
        
        public void RegisterHandler<T>(Action<T> handler) where T : MessageObject
        {
            m_MessageType = typeof(T);
            m_Handler = (obj) => handler((T)obj);
        }
        
        /// <summary>
        /// 设置消息对象
        /// </summary>
        /// <param name="messageObject">消息对象</param>
        public void SetMessageObject(MessageObject messageObject)
        {
            m_MessageObjects.Enqueue(messageObject);
        }
        
        public void Invoke()
        {
            if (m_Handler == null)
            {
                throw new ArgumentNullException($"{m_MessageType.FullName} 未注册消息处理方法");
            }

            if (m_MessageObjects.Count <= 0)
            {
                return;
            }

            var messageObject = m_MessageObjects.Dequeue();
            
            m_Handler.Invoke(messageObject);
        }
    }
}